#Data retention

rm(list = ls())

PathFiles<-"D:\\b1500_data\\QT\\OTP\\20250401\\UV"

#filename<-"DEV02_1000x_MTP Cycling Debug_5_11_21_2024 12_45_41 PM.csv"

setwd(PathFiles)

filenames_all <- list.files()[grepl("(.csv)",list.files())]
#print(filenames_all)
Data_All <- NULL

for (filename in filenames_all) {
    DataTmp<-read.csv2(filename,col.names = paste(rep("V",16),seq(1,16),sep=""))   %>% 
        select((V1)) %>% 
        separate(V1,paste(rep("V",16),seq(1,16),sep=""),",")    %>% 
        dplyr::filter(V1 %in% c("SetupTitle","DataValue","DataName"))   %>%
        mutate(setuptitle=case_when(V1=="SetupTitle" ~V2, .default = NA)) %>%
        select(where(function(x) !all(is.na(x)))) %>%
        fill(setuptitle) %>%
        dplyr::filter(V1 != "SetupTitle") %>%
        mutate(setuptitle=str_extract(setuptitle,"([a-zA-Z]{1})(.{1,100})")) %>%
        mutate(setuptitle=str_replace_all(setuptitle," ","_"))

    SetupTitle <- DataTmp$setuptitle %>% 
        as.factor() %>% 
        levels() %>% 
        as.character()

    ColNames_File <- NULL
    for (i in seq(1:length(SetupTitle))) {
        ColNames <- DataTmp %>% 
            dplyr::filter(setuptitle==SetupTitle[i]) %>%
            select(where(function(x) !all(is.na(x)))) %>% 
            slice(1L) %>% 
            as.character() %>% 
            str_trim()

        Tmp <- DataTmp %>% 
            dplyr::filter(setuptitle==SetupTitle[i]) %>%
            select(where(function(x) !all(is.na(x)))) 

        assign(SetupTitle[i],Tmp)

        assign(SetupTitle[i],get(eval(SetupTitle[i])) %>% 
            setNames(c(ColNames[1:(length(ColNames)-1)],"SetupTitle")) %>% 
            dplyr::filter((DataName != 'DataName')))

        ColNames_File <- c(ColNames_File, c(ColNames[1:(length(ColNames)-1)],"SetupTitle"))
    }

    ColNames_File <- unique(ColNames_File)

    Data_File <- NULL

    for (DataFrame in SetupTitle) {
        eval(str2expression(paste('ColNames <- colnames(',DataFrame,')')))
        eval(str2expression (paste('t<-', DataFrame)))
        for (NewCol in ColNames_File[!(ColNames_File %in% ColNames)]) {
            #print(eval(x))
            #print(t)
            eval(str2expression(paste('t<- t %>% mutate(', NewCol, '=NA)')))
            #print(head(t,1)) 
            }
        #print(colnames(t))
        t <- t %>% select(all_of(ColNames_File))
        Data_File <- rbind(Data_File,t)
    }
    DeviceSplit <- read.csv("D:\\b1500_data\\QT\\OTP\\20250320sum\\OTPTSKPlan.csv")
    Data_File <- Data_File %>% mutate(files=filename)
    Data_File <- Data_File %>% mutate(DeviceID=str_extract(files, '(O)([0-9]{1})([0-9]{1})([a-zA-Z]{1})'))
    #"Read POST\\s*(\\w+)"
    #pattern <- "Read POST\\s*(\\w+)"
    Data_File <- Data_File %>% mutate(Status=str_extract(files,"Read\\s*(\\w+)\\s*+(\\w+)\\s*+(\\w+)"))
   # Data_File <- Data_File %>% mutate(Status=str_extract(files,'([0-9]{1})([a-zA-Z]{1})([0-9]{1})'))
    Data_File <- Data_File %>% left_join(DeviceSplit, by = join_by(DeviceID == DUTName))
   # Data_File <- Data_File %>% mutate(SGsize=paste(W_Sg,L_Sg))
    #Data_File <- Data_File %>% mutate(Tpgm = case_when(Total_Pulse_Width_Value != '0.01' ~ Total_Pulse_Width_Value, .default='1E-7')) 
    Data_All <- bind_rows(Data_All, Data_File)

}

FileToBeSaved <- paste(str_extract(PathFiles,"([^/])([a-zA-z]{1,20})(.{1,20}$)"),".csv",sep="")
FilePathToBeSaved <- str_replace(PathFiles,"([^/])([a-zA-z]{1,20})(.{1,20}$)","")

write.csv(Data_All,paste(FilePathToBeSaved,FileToBeSaved, sep=""))


lab_title="OTP Initial (Read Current ~ FG length)"
lab_subtitle="SouthChip(95MIX/Cansemi) 5V Process"
lab_x="Vd(V)"
lab_y="Read Current(logA)"
panel_background_rect_fill = "white"
axis_text_x_text_size=15
axis_text_y_text_size=15
axis_text_size =15
Data_All %>%mutate(list_nLFg=as.character(list_nLFg)) %>% 
#Data_All %>% left_join(DeviceSplit, by = join_by(DeviceID == DUTName)) %>% 
    #mutate(across(DataName:files, str_trim)) %>%  
    #mutate(Tpgm = case_when(Total_Pulse_Width_Value != '0.01' ~ Total_Pulse_Width_Value, .default='1E-7')) %>% 
    #mutate(Tpgm = case_when(Total_Pulse_Width_Value == 3E-5 ~ 4E-5, .default=Tpgm)) %>% 
    #mutate(Tpgm = case_when(Total_Pulse_Width_Value == 5E-5 ~ 9E-5, .default=Tpgm)) %>% 
    #mutate(Tpgm = case_when(Total_Pulse_Width_Value == 10E-5 ~19E-5, .default=Tpgm)) %>% 
   # mutate(across(Vd:Total_Pulse_Width_Value, as.numeric)) %>% 
   # mutate(across(Tpgm, as.numeric)) %>% 
   # mutate(Vpp=str_extract(files,'([0-9]{1})(.{1})([0-9]{1})')) %>% 

    #mutate(Vpp=as.numeric(Vpp)) %>% 
   mutate(across(Vd:Iread, as.numeric)) %>% 
   
   mutate(Idread=abs(Id)) %>%
    mutate(across(Idread, as.numeric)) %>%
   mutate(across(list_nLFg, as.numeric)) %>% 
   dplyr::filter( Vg == 0 ) %>%
   #dplyr::filter(L_Sg==0.4) %>%
    ggplot(aes(x = Vd, y = Idread,color=DeviceID) ) + 
    geom_point(size=3) + geom_line() +
   scale_y_log10(limits=c(5e-8,5e-5)) +
   scale_x_continuous(limits=c(0,2.4)) +
   
    #scale_x_continuous(limits=c(0,2.6),breaks=c(0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6)) +
    geom_text(aes(label=sprintf("%.1f", Idread*1e6)),size = 5,vjust = 3) +      
    theme(axis.text = element_text(size = axis_text_size),
                                axis.title = element_text(size =axis_title_text_size),
                                axis.text.x = element_text(face = axis_text_x_text_face, color = axis_text_x_text_color,
                                                           size = axis_text_x_text_size, angle = axis_text_x_text_angle),
                                axis.text.y = element_text(face = axis_text_y_text_face, color = axis_text_y_text_color,
                                                           size = axis_text_y_text_size, angle = axis_text_y_text_angle),
                                panel.background = element_rect(fill = panel_background_rect_fill, color = "black"),
                               # panel.background = element_rect(fill = panel_background_rect_fill, color = panel_grid_major_line_color),
                               panel.grid.major = element_line(color = "lightgrey", linetype = panel_grid_major_linetype,linewidth=panel_grid_major_linewidth),
                               # panel.grid.major = element_line(color = panel_grid_major_line_color, linetype = panel_grid_major_linetype,linewidth=panel_grid_major_linewidth),
                                panel.grid.minor = element_line(color = "grey", linetype = panel_grid_minor_linetype, linewidth = panel_grid_minor_line_linewidth),
                               # panel.grid.minor = element_line(color = panel_grid_minor_line_color, linetype = panel_grid_minor_linetype, linewidth = panel_grid_minor_line_linewidth),
                                #plot.title = element_text(size = plot_title_text_size),
                                plot.title = element_text(size = 30),
                                plot.subtitle = element_text(size = 20, color = "blue"),
                                #legend.text = element_text(size = 16, color = "blue"), 
                                legend.text = element_text(size = 10, color = "blue"), 
                                #legend.text = element_text(size = plot_title_text_size),
                                legend.title = element_text(size = 10)
                                #legend.title = element_text(size = legend_title_text_size)
    ) + labs(title= lab_title, subtitle= lab_subtitle, x=lab_x, y=lab_y,tag="@AMT",)+
     theme(plot.tag = element_text(size = 18))+
    #facet_grid( W_Sg ~ L_Sg) + 
    theme(strip.text.x = element_text(size = 15, colour = "#FC0043")) + # 设置分面的字字体大小、颜色、背景、边框，
    theme(strip.text.y = element_text(size = 15, colour = "#FC0043")) 
    ggsave("BVD_1.png", width = 30, height = 20, units = "cm") 